package edu.biwu.filter02;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;

import java.io.IOException;

/**
 * ServletContext中的方法:
 *   public FilterRegistration getFilterRegistration(String filterName):根据过滤器的名称获取已注册的过滤器
 * FilterRegistration中的方法:
 *    public String getInitParameter(String name):根据参数name获取对应的value
 */

@WebFilter(filterName = "charsetFilter",urlPatterns = "/*",initParams = @WebInitParam(name = "charset",value = "UTF-8"))
//@WebFilter("/*")
public class CharsetFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        request.setCharacterEncoding("UTF-8");
        FilterRegistration charsetFilter = request.getServletContext().getFilterRegistration("charsetFilter");
        String charset = charsetFilter.getInitParameter("charset");
        response.setContentType("text/html;charset="+charset);
        chain.doFilter(request,response);////放行的时候,传递过去的response已设置好编码
    }
}
